import {Component, Input, OnDestroy, OnInit} from "@angular/core";
import {MyhttpService} from "../myhttp.service";
import {CommService} from "../comm-service";
import {ActivatedRoute, ParamMap, Router} from "@angular/router";
import {SharedService} from "../shared-service";
import {LocalStorageService} from "../local-storage-service";

@Component({
  template: `
    <div [class.page-sidebar-closed]="page_sidebar_menu_closed">
      <div class="page-container">
        <div class="page-sidebar-wrapper">
          <!-- begin sidebar-->
          <div class="page-sidebar navbar-collapse collapse">
            <ul class="page-sidebar-menu" [class.page-sidebar-menu-closed]="page_sidebar_menu_closed"
                [style.height]="sliderHeightstr">
              <!-- siderbar伸展按钮-->
              <li class="sidebar-toggler-wrapper" (click)="toggleL()">
                <div class="sidebar-toggler">
                </div>
              </li>
              <!-- siderbar伸展按钮-->
              <li *ngFor="let group of groups;index as index" [class.active]="group.isactive"
                  [class.open]="group.expand">
                <a href="javascript:void(0);" (click)="clickGTitle(group)">
                  <i class="fa fa-paper-plane-o"></i>
                  <span class="title">{{group.name}}</span>
                  <span [class.selected]="group.expand"></span>
                  <span class="arrow" [class.open]="group.expand"></span>
                </a>
                <ul class="sub-menu" *ngIf="group.expand" id="groupchildren{{index}}">
                  <li *ngFor="let m of group.subMenu">
                    <a [class.lmactive]="m.isSelect" (click)="clickLM(m)">
                      <i class="fa fa-chevron-right"></i>{{m.name}}
                    </a>
                  </li>
                </ul>
              </li>
            </ul>
          </div>
          <!-- end sidebar-->
        </div>
        <div class="page-content-wrapper">
          <div class="page-content pagecontent" [style.height]="pagecontentHei">
            <!-- begin actual content-->
            <router-outlet></router-outlet>
            <!-- end actual content-->
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [
    "li a.lmactive{background: #edf5ff!important;color:rgb(64, 158, 255)!important;}",
    ".pagecontent{background:#FFFFFF;overflow: auto}"
  ],
})
export class JcsjSliderComponent implements OnInit, OnDestroy {
  page_sidebar_menu_closed: boolean = false;
  pagecontentHei: string = "0px";
  groups: any[] = [];
  topmenurl: string;
  ldatas: any = {
    "xxglx": {
      groupslenth: 2,
      groupsname: ["数据准备", "调试助手工具"],
      lmenus: [["sjbxxx", "bqsbx", "zdsbx", "sbgjglx", "ryglx", "carglx", "yyjhx", "yyrwx", "sjcrkx"], ["zdsbx_tsgj", "bqsbx_tsgj"]]
    }
  }
  userinfo: any;
  topmenuskeyvalue: any = {};
  hasLeftmenus: any[] = [];
  sliderHeightstr: string = "0px";

  /**
   * 右侧 隐藏/显示切换
   */
  toggleL() {
    if (this.page_sidebar_menu_closed) {
      this.page_sidebar_menu_closed = false;
    } else {
      this.page_sidebar_menu_closed = true;
    }
  }

  /**
   * 根据一级菜单url， 获取二级菜单
   */
  getLmenus(): void {
    const topmenuid = this.topmenuskeyvalue[this.topmenurl];
    if (!topmenuid) {
      return
    }
    this.commservice.getroleMenus(topmenuid, this.userinfo.nowroleid, (resp) => {
      if (resp && resp.length) {
        this.handlmgroups(resp);
        this.hasLeftmenus = resp;
        const isFirstin = this.isFirstIn(resp);
        if (isFirstin) {
          this.handLmenus("init");
        } else {
          this.handLmenus("refresh");
        }
      }
    });
  }

  /**
   * 处理显示右侧菜单
   * @param {any[]} r
   */
  handlmgroups(r: any[]): void {
    this.groups.length = 0;
    const lmessageobj = this.ldatas[this.topmenurl];
    const leftgroups = lmessageobj["groupslenth"];
    for (let i = 1; i <= leftgroups; i++) {
      const lmgroupN_all = lmessageobj["lmenus"][i - 1];
      const lmgroupN_has_onorder = r.filter(function (value, index, array) {
        return (lmgroupN_all.indexOf(value.code) != -1);
      });
      // 按照 allSlidermenus 里面的排序
      const lmgroupN_has_order = this.commservice.sortMenu(lmgroupN_all, lmgroupN_has_onorder, "code");
      const lmgroupN_end = lmgroupN_has_order.map(function (item, index, array) {
        return {
          name: item.name,
          url: item.code,
          isSelect: false,
        }
      });
      if (lmgroupN_end.length > 0) {
        this.groups.push({
          name: lmessageobj["groupsname"][i - 1],
          expand: false,
          isactive: false,
          subMenu: lmgroupN_end
        });
      }
    }
    this.pagecontentHei = this.commservice.getPageHeigh();
  }

  /**
   *  判断是否是刷新
   * @param r
   * @returns {boolean}  false= 刷新
   *                      true= 非刷新，第一次进入
   */
  isFirstIn(r: any): boolean {
    const url = this.router.url;
    const targeturl = url.substring(url.lastIndexOf("/") + 1);
    const targeturl2 = targeturl.split(".")[0];
    const lmenuUrls = r.map(function (item, index, array) {
      return item.code;
    });
    return (lmenuUrls.indexOf(targeturl2) == -1);
  }

  /**
   * 处理左侧菜单的焦点   和  右侧页面的显示
   * @param {string} s
   */
  handLmenus(s: string): void {
    let lmenuid: string = "";
    if (s == "init") {
      this.router.navigate([this.groups[0].subMenu[0].url], {relativeTo: this.activerouter});
      this.setCurrentMenu(this.groups[0].subMenu[0].url);
      lmenuid = this.commservice.getLmenuId(this.hasLeftmenus, this.groups[0].subMenu[0].url);
    } else {
      const targeturl = this.router.url.substring(this.router.url.lastIndexOf("/") + 1);
      const targeturl2 = targeturl.split(".")[0];
      this.setCurrentMenu(targeturl2);
      lmenuid = this.commservice.getLmenuId(this.hasLeftmenus, targeturl2);
    }
    this.localStorageService.set("lmenuid", lmenuid);
  }

  /**
   * 处里左侧菜单分组和焦点
   * @param {string} target
   */
  setCurrentMenu(target: string): void {
    this.groups.forEach(function (value, index, array) {
      value.expand = false;
      value.isactive = false;
      const itsubmenu = value.subMenu;
      itsubmenu.forEach(function (item, index, array) {
        item.isSelect = false;
        if (target == item.url) {
          item.isSelect = true;
          value.expand = true;
          value.isactive = true;
        }
      });
    });
  }

  /**
   * 点击分组
   * @param g
   */
  clickGTitle(g: any): void {
    if (g.expand) {
      g.expand = false;
    } else {
      this.groups.forEach(function (value, index, array) {
        value.expand = false;
        value.isactive = false;
      });
      g.expand = true;
      g.isactive = true;
    }
  }

  /**
   * 点击菜单
   * @param o
   */
  clickLM(o: any): void {
    this.router.navigate([o.url], {relativeTo: this.activerouter});
    this.setCurrentMenu(o.url);
    const lmenuid = this.commservice.getLmenuId(this.hasLeftmenus, o.url);
    this.localStorageService.set("lmenuid", lmenuid);
  }

  /**
   * 用户详情
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      const aestr = this.localStorageService.get("tmenukeyValue");
      if (aestr) {
        const daestr = this.commservice.daesString(aestr);
        if (daestr) {
          this.topmenuskeyvalue = JSON.parse(daestr);
        }
        this.getLmenus();
      }
    });
  }

  /**
   * 公共子组件
   * 接受父组件传递的参数 o.topmenurl
   */
  @Input() o: any;

  constructor(private itservice: MyhttpService,
              private commservice: CommService,
              private router: Router,
              private activerouter: ActivatedRoute,
              private localStorageService: LocalStorageService,
              private sharedService: SharedService) {
  }

  ngOnInit() {
    this.sliderHeightstr = (this.commservice.getViewPort().height - this.commservice.topmenuH - this.commservice.topH) + "px";
    this.activerouter.url.subscribe(resp => {
      this.topmenurl = resp[0].path;
      this.getuserinfo();
    });
  }

  ngOnDestroy() {

  }

}
